<script lang="ts" setup>
import { computed, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  DatePicker,
  Dropdown,
  Input,
  message,
  Select,
  Table,
} from 'ant-design-vue';

import type { MenuProps, TableColumnsType } from 'ant-design-vue';

import dayjs from 'dayjs';

// 查询条件
const queryForm = ref({
  dateRange: [dayjs('2025-06'), dayjs('2025-06')],
  voucherNumber: '',
});

// 表格数据
interface VoucherRecord {
  accountSubject: string;
  creditAmount: null | number;
  debitAmount: null | number;
  id: string;
  summary: string;
  voucherDate: string;
  voucherNumber: string;
}

const tableData = ref<VoucherRecord[]>([]);

// 表格选择
const selectedRowKeys = ref<string[]>([]);
const onSelectChange = (newSelectedRowKeys: string[]) => {
  selectedRowKeys.value = newSelectedRowKeys;
};

const rowSelection = {
  onChange: onSelectChange,
  selectedRowKeys,
};

// 表格列配置
const columns: TableColumnsType<VoucherRecord> = [
  {
    dataIndex: 'summary',
    key: 'summary',
    title: '摘要',
    width: 200,
  },
  {
    dataIndex: 'accountSubject',
    key: 'accountSubject',
    title: '科目',
    width: 200,
  },
  {
    align: 'right',
    customRender: ({ text }) =>
      text
        ? `¥${text.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
        : '-',
    dataIndex: 'debitAmount',
    key: 'debitAmount',
    title: '借方金额',
    width: 150,
  },
  {
    align: 'right',
    customRender: ({ text }) =>
      text
        ? `¥${text.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
        : '-',
    dataIndex: 'creditAmount',
    key: 'creditAmount',
    title: '贷方金额',
    width: 150,
  },
];

// 排序选项
const sortOptions = [
  { label: '按日期排序', value: 'date' },
  { label: '按凭证号排序', value: 'number' },
  { label: '按金额排序', value: 'amount' },
];

const currentSort = ref('date');

// 更多查询下拉菜单
const moreQueryItems: MenuProps['items'] = [
  {
    icon: () => <IconifyIcon icon="lucide:search" />,
    key: 'advanced',
    label: '高级查询',
  },
  {
    icon: () => <IconifyIcon icon="lucide:download" />,
    key: 'export',
    label: '导出查询结果',
  },
  {
    icon: () => <IconifyIcon icon="lucide:bookmark" />,
    key: 'template',
    label: '查询模板',
  },
];

// 凭证导入下拉菜单
const importItems: MenuProps['items'] = [
  {
    icon: () => <IconifyIcon icon="lucide:file-spreadsheet" />,
    key: 'excel',
    label: 'Excel导入',
  },
  {
    icon: () => <IconifyIcon icon="lucide:file-text" />,
    key: 'csv',
    label: 'CSV导入',
  },
  {
    icon: () => <IconifyIcon icon="lucide:download" />,
    key: 'template',
    label: '下载模板',
  },
];

// 事件处理函数
const handleSearch = () => {
  // eslint-disable-next-line no-console
  console.log('触发查询逻辑', queryForm.value);
  message.info('查询功能开发中...');
};

const handleMoreQuery = ({ key }: { key: string }) => {
  // eslint-disable-next-line no-console
  console.log('更多查询:', key);
  message.info(`${key} 功能开发中...`);
};

const handleNewVoucher = () => {
  // eslint-disable-next-line no-console
  console.log('触发新增凭证逻辑');
  message.success('跳转到新增凭证页面');
  // 这里可以使用 router.push('/accounting-voucher/entry')
};

const handleImport = ({ key }: { key: string }) => {
  // eslint-disable-next-line no-console
  console.log('凭证导入:', key);
  message.info(`${key} 功能开发中...`);
};

const handleCopy = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要复制的凭证');
    return;
  }
  // eslint-disable-next-line no-console
  console.log('复制凭证:', selectedRowKeys.value);
  message.success(`已复制 ${selectedRowKeys.value.length} 条凭证`);
};

const handleDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要删除的凭证');
    return;
  }
  // eslint-disable-next-line no-console
  console.log('删除凭证:', selectedRowKeys.value);
  message.success(`已删除 ${selectedRowKeys.value.length} 条凭证`);
  selectedRowKeys.value = [];
};

const handleSortChange = (value: string) => {
  // eslint-disable-next-line no-console
  console.log('排序方式变更:', value);
  currentSort.value = value;
  message.info(
    `已切换为${sortOptions.find((item) => item.value === value)?.label}`,
  );
};

const handleReorder = () => {
  // eslint-disable-next-line no-console
  console.log('触发断号重排逻辑');
  message.success('断号重排完成');
};

// 计算选中状态提示
const selectionInfo = computed(() => {
  const count = selectedRowKeys.value.length;
  return count > 0 ? `已选择 ${count} 项` : '';
});
</script>

<template>
  <Page auto-content-height>
    <!-- 页面头部 -->
    <div class="mb-4 flex items-center justify-between">
      <!-- 左侧公司信息 -->
      <div class="flex items-center space-x-4">
        <span class="text-lg font-medium">北京神州源科技有限公司</span>
      </div>

      <!-- 右侧操作按钮 -->
      <div class="flex items-center space-x-2">
        <!-- 更多查询 -->
        <Dropdown :menu="{ items: moreQueryItems, onClick: handleMoreQuery }">
          <Button>
            更多查询
            <IconifyIcon icon="lucide:chevron-down" class="ml-1" />
          </Button>
        </Dropdown>

        <!-- 新增凭证 -->
        <Button type="primary" @click="handleNewVoucher">
          <IconifyIcon icon="lucide:plus" class="mr-1" />
          新增凭证
        </Button>

        <!-- 凭证导入 -->
        <Dropdown :menu="{ items: importItems, onClick: handleImport }">
          <Button type="primary">
            凭证导入
            <IconifyIcon icon="lucide:chevron-down" class="ml-1" />
          </Button>
        </Dropdown>

        <!-- 复制 -->
        <Button @click="handleCopy">
          <IconifyIcon icon="lucide:copy" class="mr-1" />
          复制
        </Button>

        <!-- 删除 -->
        <Button danger @click="handleDelete">
          <IconifyIcon icon="lucide:trash-2" class="mr-1" />
          删除
        </Button>

        <!-- 选择排序方式 -->
        <Select
          v-model:value="currentSort"
          :options="sortOptions"
          placeholder="选择排序方式"
          style="width: 140px"
          @change="handleSortChange"
        />

        <!-- 断号重排 -->
        <Button @click="handleReorder">断号重排</Button>
      </div>
    </div>

    <!-- 查询筛选区 -->
    <Card class="mb-4">
      <div class="flex items-center space-x-4">
        <!-- 日期范围 -->
        <div class="flex items-center space-x-2">
          <DatePicker
            v-model:value="queryForm.dateRange[0]"
            format="YYYY-MM"
            picker="month"
            placeholder="开始月份"
          />
          <span>-</span>
          <DatePicker
            v-model:value="queryForm.dateRange[1]"
            format="YYYY-MM"
            picker="month"
            placeholder="结束月份"
          />
        </div>

        <!-- 凭证号搜索 -->
        <div class="flex items-center space-x-2">
          <Input
            v-model:value="queryForm.voucherNumber"
            placeholder="凭证号"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="lucide:search" />
          </Button>
        </div>

        <!-- 选中状态提示 -->
        <div v-if="selectionInfo" class="text-sm text-blue-600">
          {{ selectionInfo }}
        </div>
      </div>
    </Card>

    <!-- 凭证表格 -->
    <Card>
      <Table
        :columns="columns"
        :data-source="tableData"
        :pagination="{
          total: 0,
          pageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }"
        :row-selection="rowSelection"
        bordered
        row-key="id"
        size="middle"
      >
        <!-- 空数据提示 -->
        <template #emptyText>
          <div class="py-8 text-center text-gray-500">
            <IconifyIcon icon="lucide:inbox" class="mb-2 text-4xl" />
            <div>暂无数据</div>
            <div class="mt-1 text-sm">请调整查询条件后重试</div>
          </div>
        </template>
      </Table>
    </Card>
  </Page>
</template>

<style scoped>
.ant-table-thead > tr > th {
  font-weight: 600;
  background-color: #fafafa;
}

.ant-btn + .ant-btn {
  margin-left: 8px;
}

.ant-dropdown-trigger {
  cursor: pointer;
}
</style>
